package com.hsmw.api.filter;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.exception.ApiException;
import com.hsmw.api.utils.ElasticSearchUtils;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.HsmwUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by pillar on 2017/3/27.
 * qq 347637454
 */
@ControllerAdvice
public class ExceptionHandlers {
    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    Logger logger = LoggerFactory.getLogger(ExceptionHandlers.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public DataResponse handle(Exception e) {
        System.out.println("e.to="+e.getMessage());
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        StackTraceElement stackTraceElement = stackTraceElements[0];
        String className =  stackTraceElement.getClassName();
        String methodName = stackTraceElement.getMethodName();
        String fileName = stackTraceElement.getFileName();
        String  lineNum  = stackTraceElement.getLineNumber()+"";

        String userId = "";
        String username= "";
        String desc= getTrace(e);
        String descInfo ="className= "+className +"\n" +"methodName = "+methodName+"\n"+"lineNum="+lineNum+"\n";
        descInfo=descInfo+desc;
        LoginUser user =  currentHsmwUserUtils.getCurrentUserInfo();
        if(StringUtils.isNotNull(user)){
            userId=user.getId();
            username=user.getUsername() +"--"+user.getName();
        }
        //ElasticSearchUtils.saveElasticInfo(userId,descInfo,username);
        if (e instanceof ApiException) {
            ApiException pillarException = (ApiException) e;
            return new DataResponse(pillarException.getStackTrace());
        }else if (e instanceof MethodArgumentTypeMismatchException){
            return new DataResponse((Object)((MethodArgumentTypeMismatchException) e).getName());
        }else {
            logger.info(e.toString());
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"操作失败，请联系管理员！");
        }
    }

    public String getTrace(Throwable t) {
        StringWriter stringWriter= new StringWriter();
        PrintWriter writer= new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer= stringWriter.getBuffer();
        return buffer.toString();
    }

    //2、
    public static String getExceptionAllinformation(Exception ex){
        String sOut = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    }
}